package fc;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import fc.entity.OaEntity;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.upgradetool.wscheck.Util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class ZH_HJ_SEND implements Action{

	@Override
	public String execute(RequestInfo info) {
		String API_NAME="ZH_HJ_SEND";

		BaseBean log = new BaseBean();

		log.writeLog("接口"+API_NAME+"开始调用-----------------------------------");

		OaEntity oe=new OaEntity();

		String requestid = info.getRequestid();
		String tablename = info.getRequestManager().getBillTableName();
		oe.setREQUESTID(requestid);



        String sql="select requestid,hjdh DANHAO,hjdjb typeno,sqry  USERID ,sqbm DEPARTMENTID,gys CUS_NO,bz CUR_ID,FKTJ,JYTJ,SXRQ,JZRQ,sz TAX_NO from  "+tablename+"  where requestid="+requestid;
        RecordSet rs = new RecordSet();
        rs.executeSql(sql);
        if(rs.next()){
            oe.setREQUESTID(Util.null2String(rs.getString("REQUESTID")));
            oe.setTYPENO(Util.null2String(rs.getString("typeno")));
            oe.setUSERID(Util.null2String(rs.getString("USERID")));
            oe.setDEPARTMENTID(Util.null2String(rs.getString("DEPARTMENTID")));
            oe.setCUS_NO(Util.null2String(rs.getString("CUS_NO")));
            oe.setCUR_ID(Util.null2String(rs.getString("CUR_ID")));
            oe.setFKTJ(Util.null2String(rs.getString("FKTJ")));
            oe.setJYTJ(Util.null2String(rs.getString("JYTJ")));
            oe.setSXRQ(Util.null2String(rs.getString("SXRQ")));
			oe.setJZRQ(Util.null2String(rs.getString("JZRQ")));

			oe.setTAX_NO(Util.null2String(rs.getString("TAX_NO")));
			oe.setDANHAO(Util.null2String(rs.getString("DANHAO")));

            if(oe.getTYPENO().equals("YHJ01")){
                oe.setJUDGE1("N");//用来判断
            }else{
                oe.setJUDGE1("Y");//用来判断
            }
        }


        String sql1="select  o1.lh LJBH,o1.dw DW,o2.bz CUR_ID,o2.sz TAX_NO,o1.dj UP,o1.bz,o1.zjyy  CAUSE  from "+tablename+"_dt1  o1,"+tablename+" o2 where o1.mainid=o2.id  and o2.requestid="+requestid;

        RecordSet rs1 = new RecordSet();
        rs1.executeSql(sql1);
        while(rs1.next()){
            List<OaEntity> dts=oe.getDT1();
            OaEntity dt1=new OaEntity();
            dt1.setLJBH(Util.null2String(rs1.getString("LJBH")));
            dt1.setDW(Util.null2String(rs1.getString("DW")));
            dt1.setCUR_ID(Util.null2String(rs1.getString("CUR_ID")));
            dt1.setTAX_NO(Util.null2String(rs1.getString("TAX_NO")));
            dt1.setUP(Util.null2String(rs1.getString("UP")));
            dt1.setREM(Util.null2String(rs1.getString("REM")));
			dt1.setCAUSE(Util.null2String(rs1.getString("CAUSE")));
			dts.add(dt1);
            oe.setDT1(dts);
        }



		String testparam="";
		log.writeLog("接口"+API_NAME+"参数开始-----------------------------------"+oe.getREQUESTID());

		log.writeLog("main-----------------------------------");
		log.writeLog("REQUESTID :"+oe.getREQUESTID());
		testparam="";
		log.writeLog("dt1-----------------------------------");


		for(int i=0;i<oe.getDT1().size();i++){
			log.writeLog("料件编号 LJBH:"+oe.getDT1().get(i).getLJBH()+
					",单价 UP:"+oe.getDT1().get(i).getUP()
			);
			if (!"".equals(testparam)){
				testparam=testparam+",";
			}
			testparam+=
					"{"+
							"\"seq_no\": \""+(i+1)+"\",  "+//序号，同一单不可以相同，必填
							"\"item_no\": \""+oe.getDT1().get(i).getLJBH()+"\",  "+//料号，必填
							"\"item_feature_no\": \" \","+
							"\"series_no\": \"\","+
							"\"item_category\": \"\","+
							"\"vendor_item_no\": \"\","+
							"\"program_job_no\": \"\","+
							"\"op_seq\": \"\","+
							"\"process_no\": \"\","+
							"\"reason_code\": \"\","+
							"\"unit\": \""+oe.getDT1().get(i).getDW()+"\",   "+//物料单位，必填
							"\"currency_no\": \""+oe.getDT1().get(i).getCUR_ID()+"\","+//，必填
							"\"tax_no\": \""+oe.getDT1().get(i).getTAX_NO()+"\",  "+//税种，必填
							"\"reason_prc_increase\": \""+oe.getDT1().get(i).getCAUSE()+"\",  "+//涨价原因，当当前价格高于以往，要在这里填原因

							"\"remark\": \""+oe.getDT1().get(i).getREM()+"\","+
							"\"price\": \""+oe.getDT1().get(i).getUP()+"\",  "+//单价，必填
							"\"is_qty_valuation\": \"N\",  "+ //是否分量计，必填（若这里为Y，则下面的分量明细必填，否则分量计价明细里面可以为空）
							"\"pricing_valuation_detail\": ["+
							"]"+
							"}";

		}


		DateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String  timestamp= format.format(new Date());
		DateFormat formataa = new SimpleDateFormat("yyyy-MM-dd");
		String createdate = formataa.format(new Date());
		String creater=oe.getUSERID();
		String bumen=oe.getDEPARTMENTID();

		//oe.setREQUESTID(timestamp);

		String json_param=
				"{"+
						"\"key\": \"a3b67072afa24b1e5d15e6486dd83bc8\","+
						"\"type\": \"sync\","+
						"\"host\": {"+
						"\"prod\": \"OAPI\","+
						"\"ip\": \"10.100.96.96\","+
						"\"lang\": \"zh_CN\","+
						"\"timestamp\": \""+timestamp+"\","+
						"\"acct\": \"tiptop\""+
						"},"+
						"\"service\": {"+
						"\"prod\": \"T100\","+
						"\"name\": \"oapi.po.pricing.crt\","+
						"\"ip\": \"10.100.96.96\","+
						"\"id\": \"topprod\""+
						"},"+
						"\"datakey\": {"+
						"\"EntId\": \"2\","+
						"\"CompanyId\": \"ZH00\","+
						"\"doc_type_no\": \""+oe.getTYPENO()+"\",   "+ //YJH01是标准采购核价，YHJ02是委的， YHJ03是委外返修的，必填
						"\"item_no\": \"\""+
						"},"+
						"\"payload\": {"+
						"\"std_data\": {"+
						"\"parameter\": {"+
						"\"enterprise_no\": \"2\", "+//必给，与上面ENTID一致
						"\"site_no\": \"ZH00\","+
						"\"is_digiwin_product\": \"Y\","+
						"\"pricing_list_master\": ["+
						"{"+
						"\"source_no\": \""+oe.getREQUESTID()+"\",   "+//来源单号， 每次提次不可以相同，必填
						"\"doc_type_no\": \""+oe.getTYPENO()+"\", "+ //必填，与上面一致
						"\"outsourcing_type\": \""+oe.getJUDGE1()+"\",   "+//是否是委外，必填
						"\"doc_date\": \""+createdate+"\",  "+//必填
						"\"applicant_no\": \""+creater+"\",  "+ //申请人，必填
						"\"application_department\": \""+bumen+"\",   "+//申请人所在部门编号，必填
						"\"supplier\": \""+oe.getCUS_NO()+"\",  "+ //供应商编号，必填
						"\"currency_no\": \""+oe.getCUR_ID()+"\","+//，必填
						"\"tax_no\": \""+oe.getTAX_NO()+"\",   "+//税种，必填
						"\"payment_condition\": \""+oe.getFKTJ()+"\",   "+//付款条件，必填
						"\"trade_condition\": \""+oe.getJYTJ()+"\",  "+//交易条件，必填
						"\"approval_content\": \"1\","+
						"\"effective_date\": \""+oe.getSXRQ()+"\", "+  //生效开始日，必填
						"\"expiration_date\": \""+oe.getJZRQ()+"\", "+  //截止日期
						"\"price_valuation_target_control\": \"1\","+
						"\"price_valuation_control\": \"1\","+
						"\"is_qty_valuation\": \"N\",  "+//分量计价否
						"\"remark\": \""+oe.getDANHAO()+"\","+
						"\"modify_no\": \""+creater+"\","+
						"\"create_date\": \""+createdate+"\","+
						"\"doc_approve_set\": \"N\","+
						"\"pricing_list_detail\": ["+

						testparam+

						"]"+
						"}"+
						"]"+
						"}"+
						"}"+
						"}"+
						"}";


		log.writeLog("接口"+API_NAME+"json_param:"+json_param);

		String result="ERROR";
		if(!"".equals(testparam)){
			String data = HttpRequest.post(FcHttpCon.ZH_YFSY_XQ).body(json_param).execute().body();
			log.writeLog("接口"+API_NAME+"返回-----------------------------------"+data);
			try {
				Object succesResponse = JSON.parse(data);
				Map map = (Map)succesResponse;
				Map map1 = (Map)map.get("payload");
				Map map2 = (Map)map1.get("std_data");
				Map map3 = (Map)map2.get("execution");
				Map map4 = (Map) map2.get("parameter");

				if("0".equals(map3.get("code"))){
					result="SUCCESS";
				}else{
					//result="ERROR";
					JSONArray jsonArray = new JSONArray(map4.get("pricing_list_master"));
					for( int i=0;i<jsonArray.size();i++){
						JSONObject infog = new JSONObject((Map<String, Object>) jsonArray.get(i));
						Map mapg = (Map) infog;
						result= mapg.get("execute_description").toString();//1
					}
				}


			} catch (Exception e) {}
		}else{
			result="NOTNEED";
		}

		if("SUCCESS".equals(result)){
			//记录数据
			RecordSet rsg = new RecordSet();
			String sqlg="INSERT INTO FC_API_DIAOYONG_JILU VALUES('"+API_NAME+"',"+requestid+",GETDATE())";
			rsg.executeSql(sqlg);
		}else if("NOTNEED".equals(result)){
		}else{
			if("ERROR".equals(result)) {
				info.getRequestManager().setMessagecontent("接口调用失败无法提交！请联系管理员具体查看");
			}else{
				info.getRequestManager().setMessagecontent(result);
			}
			return FAILURE_AND_CONTINUE;
		}
		return SUCCESS;


	}

	public static String sendPost(String url, String param) {

		PrintWriter out = null;
		BufferedReader in = null;
		StringBuilder result = new StringBuilder();
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Accept-Charset", "UTF-8");
			conn.setRequestProperty("contentType", "UTF-8");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result.append(line);
			}
		} catch (Exception e) {
//			System.out.println("发送 POST 请求出现异常！" + e);
			result = new StringBuilder("{\"msg\":\"SB\",\"errCode\":\"1001\"}");
			e.printStackTrace();
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result.toString();
	}





} 